﻿using System;
using System.Collections.Generic;

using System.Text;
using RoughJs.Helper;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// </summary>
    public class Node
    {
        public const int
        FUNCTION_PROP = 1,
        LOCAL_PROP = 2,
        LOCAL_BLOCK_PROP = 3,
        REGEXP_PROP = 4,
        CASEARRAY_PROP = 5,
            /*
                the following properties are defined and manipulated by the
                optimizer -
                TARGETBLOCK_PROP - the block referenced by a branch node
                VARIABLE_PROP - the variable referenced by a BIND or NAME node
                ISNUMBER_PROP - this node generates code on Number children and
                                delivers a Number result (as opposed to Objects)
                DIRECTCALL_PROP - this call node should emit code to test the function
                                  object against the known class and call direct if it
                                  matches.
            */

        TARGETBLOCK_PROP = 6,
        VARIABLE_PROP = 7,
        ISNUMBER_PROP = 8,
        DIRECTCALL_PROP = 9,
        SPECIALCALL_PROP = 10,
        SKIP_INDEXES_PROP = 11, // array of skipped indexes of array literal
        OBJECT_IDS_PROP = 12, // array of properties for object literal
        INCRDECR_PROP = 13, // pre or post type of increment/decrement
        CATCH_SCOPE_PROP = 14, // index of catch scope block in catch
        LABEL_ID_PROP = 15, // label id: code generation uses it
        MEMBER_TYPE_PROP = 16, // type of element access operation
        NAME_PROP = 17, // property name
        CONTROL_BLOCK_PROP = 18, // flags a control block that can drop off
        PARENTHESIZED_PROP = 19, // expression is parenthesized
        GENERATOR_END_PROP = 20,
        DESTRUCTURING_ARRAY_LENGTH = 21,
        DESTRUCTURING_NAMES = 22,
        LAST_PROP = 22;

        // values of ISNUMBER_PROP to specify
        // which of the children are Number types
        public const int
            BOTH = 0,
            LEFT = 1,
            RIGHT = 2;

        public const int    // values for SPECIALCALL_PROP
            NON_SPECIALCALL = 0,
            SPECIALCALL_EVAL = 1,
            SPECIALCALL_WITH = 2;

        public static int   // flags for INCRDECR_PROP
            DECR_FLAG = 0x1,
            POST_FLAG = 0x2;

        public static int   // flags for MEMBER_TYPE_PROP
            PROPERTY_FLAG = 0x1, // property access: element is valid name
            ATTRIBUTE_FLAG = 0x2, // x.@y or x..@y
            DESCENDANTS_FLAG = 0x4; // x..y or x..@i
        public class NumberNode : Node
        {
            public NumberNode(double number)
                : base(Token.NUMBER)
            { this.number = number; }
            public double number;
        }
        public class StringNode : Node
        {
            public StringNode(int type, String str) : base(type) { this.str = str; }
            public String str;
            public Node.Scope scope;
        }
        public class Jump : Node
        {
            public Jump(int type) : base(type) { }


            public Jump(int type, int lineno) : base(type, lineno) { }


            public Jump(int type, Node child) : base(type, child) { }

            public Jump(int type, Node child, int lineno) : base(type, child, lineno) { }


            public Jump getJumpStatement()
            {
                if (!(type == Token.BREAK || type == Token.CONTINUE)) Kit.codeBug();
                return jumpNode;
            }

            public void setJumpStatement(Jump jumpStatement)
            {
                if (!(type == Token.BREAK || type == Token.CONTINUE)) Kit.codeBug();
                if (jumpStatement == null) Kit.codeBug();
                if (this.jumpNode != null) Kit.codeBug(); //only once
                this.jumpNode = jumpStatement;
            }

            public Node getDefault()
            {
                if (!(type == Token.SWITCH)) Kit.codeBug();
                return target2;
            }

            public void setDefault(Node defaultTarget)
            {
                if (!(type == Token.SWITCH)) Kit.codeBug();
                if (defaultTarget.type != Token.TARGET) Kit.codeBug();
                if (target2 != null) Kit.codeBug(); //only once
                target2 = defaultTarget;
            }

            public Node getFinally()
            {
                if (!(type == Token.TRY)) Kit.codeBug();
                return target2;
            }

            public void setFinally(Node finallyTarget)
            {
                if (!(type == Token.TRY)) Kit.codeBug();
                if (finallyTarget.type != Token.TARGET) Kit.codeBug();
                if (target2 != null) Kit.codeBug(); //only once
                target2 = finallyTarget;
            }

            public Jump getLoop()
            {
                if (!(type == Token.LABEL)) Kit.codeBug();
                return jumpNode;
            }

            public void setLoop(Jump loop)
            {
                if (!(type == Token.LABEL)) Kit.codeBug();
                if (loop == null) Kit.codeBug();
                if (jumpNode != null) Kit.codeBug(); //only once
                jumpNode = loop;
            }

            public Node getContinue()
            {
                if (type != Token.LOOP) Kit.codeBug();
                return target2;
            }

            public void setContinue(Node continueTarget)
            {
                if (type != Token.LOOP) Kit.codeBug();
                if (continueTarget.type != Token.TARGET) Kit.codeBug();
                if (target2 != null) Kit.codeBug(); //only once
                target2 = continueTarget;
            }

            public Node target;
            public Node target2;
            public Jump jumpNode;
        }
        public class Symbol
        {
            public Symbol(int declType, String name)
            {
                this.declType = declType;
                this.name = name;
                this.index = -1;
            }
            /**
             * One of Token.FUNCTION, Token.LP (for parameters), Token.VAR, 
             * Token.LET, or Token.CONST
             */
            public int declType;
            public int index;
            public String name;
            public Node.Scope containingTable;
        }

        public class Scope : Jump
        {
            public Scope(int nodeType) : base(nodeType) { }
            public Scope(int nodeType, int lineno) : base(nodeType, lineno) { }
            public Scope(int nodeType, Node n, int lineno) : base(nodeType, n, lineno) { }
            public static Scope splitScope(Scope scope)
            {
                Scope result = new Scope(scope.getType());
                result.symbolTable = scope.symbolTable;
                scope.symbolTable = null;
                result.parent = scope.parent;
                scope.parent = result;
                result.top = scope.top;
                return result;
            }

            public static void joinScopes(Scope source, Scope dest)
            {
                source.ensureSymbolTable();
                dest.ensureSymbolTable();
                if (!(DictionaryHelper<String>.Like(source.symbolTable.Keys, dest.symbolTable.Keys)))
                {
                    throw Kit.codeBug();
                }
                //KeyValuePair<String,Symbol>[] keyValue = new KeyValuePair<string,Symbol>[5];
                foreach (String key in source.symbolTable.Keys)
                {
                    dest.symbolTable[key] = source.symbolTable[key];
                }
            }

            public void setParent(Scope parent)
            {
                this.parent = parent;
                this.top = parent == null ? ((ScriptOrFnNode)this) : parent.top;
            }

            public Scope getParentScope()
            {
                return parent;
            }
            /// <summary>
            /// 得到一个定义域
            /// </summary>
            /// <param name="name"></param>
            /// <returns></returns>
            public Scope getDefiningScope(String name)
            {
                for (Scope sn = this; sn != null; sn = sn.parent)
                {
                    if (sn.symbolTable == null)
                        continue;
                    if (sn.symbolTable.ContainsKey(name))
                        return sn;
                }
                return null;
            }
            /// <summary>
            /// 得到符号表
            /// </summary>
            /// <param name="name"></param>
            /// <returns></returns>
            public Symbol getSymbol(String name)
            {
                return symbolTable == null ? null : symbolTable[name];
            }

            public void putSymbol(String name, Symbol symbol)
            {
                ensureSymbolTable();
                symbolTable[name] = symbol;
                symbol.containingTable = this;
                top.addSymbol(symbol);
            }

            public IDictionary<String, Symbol> getSymbolTable()
            {
                return symbolTable;
            }
            //创建一个符号表
            private void ensureSymbolTable()
            {
                if (symbolTable == null)
                {
                    symbolTable = new Dictionary<String, Symbol>(5);
                }
            }

            public IDictionary<String, Symbol> symbolTable;
            private Scope parent;
            private ScriptOrFnNode top;
        }
        public class PropListItem
        {
            public PropListItem next;
            public int type;
            public int intValue;
            public Object objectValue;
        }
        #region Node
        public Node(int nodeType)
        {
            type = nodeType;
        }

        public Node(int nodeType, Node child)
        {
            type = nodeType;
            first = last = child;
            child.next = null;
        }

        public Node(int nodeType, Node left, Node right)
        {
            type = nodeType;
            first = left;
            last = right;
            left.next = right;
            right.next = null;
        }

        public Node(int nodeType, Node left, Node mid, Node right)
        {
            type = nodeType;
            first = left;
            last = right;
            left.next = mid;
            mid.next = right;
            right.next = null;
        }

        public Node(int nodeType, int line)
        {
            type = nodeType;
            lineno = line;
        }

        public Node(int nodeType, Node child, int line)
            : this(nodeType, child)
        {

            lineno = line;
        }

        public Node(int nodeType, Node left, Node right, int line)
            : this(nodeType, left, right)
        {

            lineno = line;
        }

        public Node(int nodeType, Node left, Node mid, Node right, int line)
            : this(nodeType, left, mid, right)
        {
            lineno = line;
        }
       /// <summary>
       /// 当类型为数值时调用
       /// </summary>
       /// <returns></returns>
        public double getDouble()
        {
            return ((NumberNode)this).number;
        }

        public void setDouble(double number)
        {
            ((NumberNode)this).number = number;
        }
        /// <summary>
        /// 创建数值型节点
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static Node newNumber(double number)
        {
            return new NumberNode(number);
        }

        /// <summary>
        /// 创建一个字符型节点
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Node newString(String str)
        {
            return new StringNode(Token.STRING, str);
        }

        /// <summary>
        /// 创建一个字符型节点
        /// </summary>
        /// <param name="type"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Node newString(int type, String str)
        {
            return new StringNode(type, str);
        }

        public int getType()
        {
            return type;
        }

        public void setType(int type)
        {
            this.type = type;
        }

        public bool hasChildren()
        {
            return first != null;
        }

        public Node getFirstChild()
        {
            return first;
        }

        public Node getLastChild()
        {
            return last;
        }

        public Node getNext()
        {
            return next;
        }

        public Node getChildBefore(Node child)
        {
            if (child == first)
                return null;
            Node n = first;
            while (n.next != child)
            {
                n = n.next;
                if (n == null)
                    throw new Exception("node is not a child");
            }
            return n;
        }

        public Node getLastSibling()
        {
            Node n = this;
            while (n.next != null)
            {
                n = n.next;
            }
            return n;
        }

        public void addChildToFront(Node child)
        {
            child.next = first;
            first = child;
            if (last == null)
            {
                last = child;
            }
        }

        public void addChildToBack(Node child)
        {
            child.next = null;
            if (last == null)
            {
                first = last = child;
                return;
            }
            last.next = child;
            last = child;
        }

        public void addChildrenToFront(Node children)
        {
            Node lastSib = children.getLastSibling();
            lastSib.next = first;
            first = children;
            if (last == null)
            {
                last = lastSib;
            }
        }

        public void addChildrenToBack(Node children)
        {
            if (last != null)
            {
                last.next = children;
            }
            last = children.getLastSibling();
            if (first == null)
            {
                first = children;
            }
        }

        public Object getProp(int propType)
        {
            PropListItem item = lookupProperty(propType);
            if (item == null) { return null; }
            return item.objectValue;
        }

        public int getIntProp(int propType, int defaultValue)
        {
            PropListItem item = lookupProperty(propType);
            if (item == null) { return defaultValue; }
            return item.intValue;
        }

        private PropListItem ensureProperty(int propType)
        {
            PropListItem item = lookupProperty(propType);
            if (item == null)
            {
                item = new PropListItem();
                item.type = propType;
                item.next = propListHead;
                propListHead = item;
            }
            return item;
        }

        private PropListItem lookupProperty(int propType)
        {
            PropListItem x = propListHead;
            while (x != null && propType != x.type)
            {
                x = x.next;
            }
            return x;
        }

        public void putIntProp(int propType, int prop)
        {
            PropListItem item = ensureProperty(propType);
            item.intValue = prop;
        }

        public bool hasSideEffects()
        {
            switch (type)
            {
                case Token.EXPR_VOID:
                case Token.COMMA:
                    if (last != null)
                        return last.hasSideEffects();
                    else
                        return true;

                case Token.HOOK:
                    if (first == null ||
                        first.next == null ||
                        first.next.next == null)
                        Kit.codeBug();
                    return first.next.hasSideEffects() &&
                           first.next.next.hasSideEffects();

                case Token.AND:
                case Token.OR:
                    if (first == null || last == null)
                        Kit.codeBug();
                    return first.hasSideEffects() || last.hasSideEffects();

                case Token.ERROR:         // Avoid cascaded error messages
                case Token.EXPR_RESULT:
                case Token.ASSIGN:
                case Token.ASSIGN_ADD:
                case Token.ASSIGN_SUB:
                case Token.ASSIGN_MUL:
                case Token.ASSIGN_DIV:
                case Token.ASSIGN_MOD:
                case Token.ASSIGN_BITOR:
                case Token.ASSIGN_BITXOR:
                case Token.ASSIGN_BITAND:
                case Token.ASSIGN_LSH:
                case Token.ASSIGN_RSH:
                case Token.ASSIGN_URSH:
                case Token.ENTERWITH:
                case Token.LEAVEWITH:
                case Token.RETURN:
                case Token.GOTO:
                case Token.IFEQ:
                case Token.IFNE:
                case Token.NEW:
                case Token.DELPROP:
                case Token.SETNAME:
                case Token.SETPROP:
                case Token.SETELEM:
                case Token.CALL:
                case Token.THROW:
                case Token.RETHROW:
                case Token.SETVAR:
                case Token.CATCH_SCOPE:
                case Token.RETURN_RESULT:
                case Token.SET_REF:
                case Token.DEL_REF:
                case Token.REF_CALL:
                case Token.TRY:
                case Token.SEMI:
                case Token.INC:
                case Token.DEC:
                case Token.EXPORT:
                case Token.IMPORT:
                case Token.IF:
                case Token.ELSE:
                case Token.SWITCH:
                case Token.WHILE:
                case Token.DO:
                case Token.FOR:
                case Token.BREAK:
                case Token.CONTINUE:
                case Token.VAR:
                case Token.CONST:
                case Token.LET:
                case Token.LETEXPR:
                case Token.WITH:
                case Token.WITHEXPR:
                case Token.CATCH:
                case Token.FINALLY:
                case Token.BLOCK:
                case Token.LABEL:
                case Token.TARGET:
                case Token.LOOP:
                case Token.JSR:
                case Token.SETPROP_OP:
                case Token.SETELEM_OP:
                case Token.LOCAL_BLOCK:
                case Token.SET_REF_OP:
                case Token.YIELD:
                case Token.UNDEFINED:
                    return true;

                default:
                    return false;
            }
        }

        /** Can only be called when node has String context. */
        public String getString()
        {
            return ((StringNode)this).str;
        }

        /** Can only be called when node has String context. */
        public void setString(String s)
        {
            if (s == null) Kit.codeBug();
            ((StringNode)this).str = s;
        }

        public void removeChild(Node child)
        {
            Node prev = getChildBefore(child);
            if (prev == null)
                first = first.next;
            else
                prev.next = child.next;
            if (child == last) last = prev;
            child.next = null;
        }

        public void putProp(int propType, Object prop)
        {
            if (prop == null)
            {
                removeProp(propType);
            }
            else
            {
                PropListItem item = ensureProperty(propType);
                item.objectValue = prop;
            }
        }
        public void removeProp(int propType)
        {
            PropListItem x = propListHead;
            if (x != null)
            {
                PropListItem prev = null;
                while (x.type != propType)
                {
                    prev = x;
                    x = x.next;
                    if (x == null) { return; }
                }
                if (prev == null)
                {
                    propListHead = x.next;
                }
                else
                {
                    prev.next = x.next;
                }
            }
        }

        public void replaceChild(Node child, Node newChild)
        {
            newChild.next = child.next;
            if (child == first)
            {
                first = newChild;
            }
            else
            {
                Node prev = getChildBefore(child);
                prev.next = newChild;
            }
            if (child == last)
                last = newChild;
            child.next = null;
        }

        public void replaceChildAfter(Node prevChild, Node newChild)
        {
            Node child = prevChild.next;
            newChild.next = child.next;
            prevChild.next = newChild;
            if (child == last)
                last = newChild;
            child.next = null;
        }


        /**
    * Checks that every return usage in a function body is consistent with the
    * requirements of strict-mode.
    * @return true if the function satisfies strict mode requirement.
    */
        public bool hasConsistentReturnUsage()
        {
            int n = endCheck();
            return (n & END_RETURNS_VALUE) == 0 ||
                   (n & (END_DROPS_OFF | END_RETURNS | END_YIELDS)) == 0;
        }

        /**
     * When a break is encountered annotate the statement being broken
     * out of by setting its CONTROL_BLOCK_PROP property.
     * @return logical OR of END_* flags
     */
        private int endCheckBreak()
        {
            Node n = ((Jump)this).jumpNode;
            n.putIntProp(CONTROL_BLOCK_PROP, END_DROPS_OFF);
            return END_UNREACHED;
        }

        /**
     * Return statement in the loop body must be consistent. The default
     * assumption for any kind of a loop is that it will eventually terminate.
     * The only exception is a loop with a constant true condition. Code that
     * follows such a loop is examined only if one can statically determine
     * that there is a break out of the loop.
     *  for(<> ; <>; <>) {}
     *  for(<> in <> ) {}
     *  while(<>) { }
     *  do { } while(<>)
     * @return logical OR of END_* flags
     */
        private int endCheckLoop()
        {
            Node n;
            int rv = END_UNREACHED;

            // To find the loop body, we look at the second to last node of the
            // loop node, which should be the predicate that the loop should
            // satisfy.
            // The target of the predicate is the loop-body for all 4 kinds of
            // loops.
            for (n = first; n.next != last; n = n.next)
            {
                /* skip */
            }
            if (n.type != Token.IFEQ)
                return END_DROPS_OFF;

            // The target's next is the loop body block
            rv = ((Jump)n).target.next.endCheck();

            // check to see if the loop condition is true
            if (n.first.type == Token.TRUE)
                rv &= ~END_DROPS_OFF;

            // look for effect of breaks
            rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED);

            return rv;
        }

        /**
     * A labelled statement implies that there maybe a break to the label. The
     * function processes the labelled statement and then checks the
     * CONTROL_BLOCK_PROP property to see if there is ever a break to the
     * particular label.
     * @return logical OR of END_* flags
     */
        private int endCheckLabel()
        {
            int rv = END_UNREACHED;

            rv = next.endCheck();
            rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED);

            return rv;
        }

        /**
     * endCheck() examines the body of a function, doing a basic reachability
     * analysis and returns a combination of flags END_* flags that indicate
     * how the function execution can terminate. These constitute only the
     * pessimistic set of termination conditions. It is possible that at
     * runtime certain code paths will never be actually taken. Hence this
     * analysis will flag errors in cases where there may not be errors.
     * @return logical OR of END_* flags
     */
        private int endCheck()
        {
            switch (type)
            {
                case Token.BREAK:
                    return endCheckBreak();

                case Token.EXPR_VOID:
                    if (this.first != null)
                        return first.endCheck();
                    return END_DROPS_OFF;

                case Token.YIELD:
                    return END_YIELDS;

                case Token.CONTINUE:
                case Token.THROW:
                    return END_UNREACHED;

                case Token.RETURN:
                    if (this.first != null)
                        return END_RETURNS_VALUE;
                    else
                        return END_RETURNS;

                case Token.TARGET:
                    if (next != null)
                        return next.endCheck();
                    else
                        return END_DROPS_OFF;

                case Token.LOOP:
                    return endCheckLoop();

                case Token.LOCAL_BLOCK:
                case Token.BLOCK:
                    // there are several special kinds of blocks
                    if (first == null)
                        return END_DROPS_OFF;

                    switch (first.type)
                    {
                        case Token.LABEL:
                            return first.endCheckLabel();

                        case Token.IFNE:
                            return first.endCheckIf();

                        case Token.SWITCH:
                            return first.endCheckSwitch();

                        case Token.TRY:
                            return first.endCheckTry();

                        default:
                            return endCheckBlock();
                    }

                default:
                    return END_DROPS_OFF;
            }
        }

        /**
     * A general block of code is examined statement by statement. If any
     * statement (even compound ones) returns in all branches, then subsequent
     * statements are not examined.
     * @return logical OR of END_* flags
     */
        private int endCheckBlock()
        {
            Node n;
            int rv = END_DROPS_OFF;

            // check each statment and if the statement can continue onto the next
            // one, then check the next statement
            for (n = first; ((rv & END_DROPS_OFF) != 0) && n != null; n = n.next)
            {
                rv &= ~END_DROPS_OFF;
                rv |= n.endCheck();
            }
            return rv;
        }

        /**
     * If the block has a finally, return consistency is checked in the
     * finally block. If all code paths in the finally returns, then the
     * returns in the try-catch blocks don't matter. If there is a code path
     * that does not return or if there is no finally block, the returns
     * of the try and catch blocks are checked for mismatch.
     * @return logical OR of END_* flags
     */
        private int endCheckTry()
        {
            Node n;
            int rv = END_UNREACHED;

            // check the finally if it exists
            n = ((Jump)this).getFinally();
            if (n != null)
            {
                rv = n.next.first.endCheck();
            }
            else
            {
                rv = END_DROPS_OFF;
            }

            // if the finally block always returns, then none of the returns
            // in the try or catch blocks matter
            if ((rv & END_DROPS_OFF) != 0)
            {
                rv &= ~END_DROPS_OFF;

                // examine the try block
                rv |= first.endCheck();

                // check each catch block
                n = ((Jump)this).target;
                if (n != null)
                {
                    // point to the first catch_scope
                    for (n = n.next.first; n != null; n = n.next.next)
                    {
                        // check the block of user code in the catch_scope
                        rv |= n.next.first.next.first.endCheck();
                    }
                }
            }

            return rv;
        }

        /**
     * Add 'child' after 'node'.
     */
        public void addChildAfter(Node newChild, Node node)
        {
            if (newChild.next != null)
                throw new Exception(
                          "newChild had siblings in addChildAfter");
            newChild.next = node.next;
            node.next = newChild;
            if (last == node)
                last = newChild;
        }

        /**
     * Consistency of return statements is checked between the case statements.
     * If there is no default, then the switch can fall through. If there is a
     * default,we check to see if all code paths in the default return or if
     * there is a code path that can fall through.
     * @return logical OR of END_* flags
     */
        private int endCheckSwitch()
        {
            Node n;
            int rv = END_UNREACHED;

            // examine the cases
            for (n = first.next; n != null; n = n.next)
            {
                if (n.type == Token.CASE)
                {
                    rv |= ((Jump)n).target.endCheck();
                }
                else
                    break;
            }

            // we don't care how the cases drop into each other
            rv &= ~END_DROPS_OFF;

            // examine the default
            n = ((Jump)this).getDefault();
            if (n != null)
                rv |= n.endCheck();
            else
                rv |= END_DROPS_OFF;

            // remove the switch block
            rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED);

            return rv;
        }
        /**
     * Returns in the then and else blocks must be consistent with each other.
     * If there is no else block, then the return statement can fall through.
     * @return logical OR of END_* flags
     */
        private int endCheckIf()
        {
            Node th, el;
            int rv = END_UNREACHED;

            th = next;
            el = ((Jump)this).target;

            rv = th.endCheck();

            if (el != null)
                rv |= el.endCheck();
            else
                rv |= END_DROPS_OFF;

            return rv;
        }

        public static Node newTarget()
        {
            return new Node(Token.TARGET);
        }

        public int getLineno()
        {
            return lineno;
        }
        public int getExistingIntProp(int propType)
        {
            PropListItem item = lookupProperty(propType);
            if (item == null) { Kit.codeBug(); }
            return item.intValue;
        }


        /// <summary>
        /// 当节点有String上下文的时候才会被调用    
        /// </summary>
        /// <returns></returns>
        public Scope getScope()
        {
            return ((StringNode)this).scope;
        }

        /// <summary>
        /// 当节点有String上下文的时候才会被调用    
        /// </summary>
        /// <param name="s"></param>
        public void setScope(Scope s)
        {
            if (s == null) Kit.codeBug();
            if (!(this is StringNode))
            {
                throw Kit.codeBug();
            }
            ((StringNode)this).scope = s;
        }


        private static  String propToString(int propType)
    {
        if (Token.printTrees) {
            // If Context.printTrees is false, the compiler
            // can remove all these strings.
            switch (propType) {
                case FUNCTION_PROP:      return "function";
                case LOCAL_PROP:         return "local";
                case LOCAL_BLOCK_PROP:   return "local_block";
                case REGEXP_PROP:        return "regexp";
                case CASEARRAY_PROP:     return "casearray";

                case TARGETBLOCK_PROP:   return "targetblock";
                case VARIABLE_PROP:      return "variable";
                case ISNUMBER_PROP:      return "isnumber";
                case DIRECTCALL_PROP:    return "directcall";

                case SPECIALCALL_PROP:   return "specialcall";
                case SKIP_INDEXES_PROP:  return "skip_indexes";
                case OBJECT_IDS_PROP:    return "object_ids_prop";
                case INCRDECR_PROP:      return "incrdecr_prop";
                case CATCH_SCOPE_PROP:   return "catch_scope_prop";
                case LABEL_ID_PROP:      return "label_id_prop";
                case MEMBER_TYPE_PROP:   return "member_type_prop";
                case NAME_PROP:          return "name_prop";
                case CONTROL_BLOCK_PROP: return "control_block_prop";
                case PARENTHESIZED_PROP: return "parenthesized_prop";
                case GENERATOR_END_PROP: return "generator_end";
                case DESTRUCTURING_ARRAY_LENGTH:
                                         return "destructuring_array_length";
                case DESTRUCTURING_NAMES:return "destructuring_names";

                default: Kit.codeBug(); break;
            }
        }
        return null;
    }
         public  int labelId()
    {
        if (type != Token.TARGET && type != Token.YIELD) Kit.codeBug();
        return getIntProp(LABEL_ID_PROP, -1);
    }

    public void labelId(int labelId)
    {
        if (type != Token.TARGET  && type != Token.YIELD) Kit.codeBug();
        putIntProp(LABEL_ID_PROP, labelId);
    }

        public override  String ToString()
        {
            if (Token.printTrees)
            {
                StringBuilder sb = new StringBuilder();
                toString(new ObjToIntMap(), sb);
                return sb.ToString();
            }
            return type.ToString();
        }

        private void toString(ObjToIntMap printIds, StringBuilder sb)
    {
        if (Token.printTrees) {
            sb.Append(Token.name(type));
            if (this is StringNode) {
                sb.Append(' ');
                sb.Append(getString());
                Scope scope = getScope();
                if (scope != null) {
                    sb.Append("[scope: ");
                    appendPrintId(scope, printIds, sb);
                    sb.Append("]");
                }
            } else if (this is Node.Scope) {
                if (this is ScriptOrFnNode) {
                    ScriptOrFnNode sof = (ScriptOrFnNode)this;
                    if (this is FunctionNode) {
                        FunctionNode fn = (FunctionNode)this;
                        sb.Append(' ');
                        sb.Append(fn.getFunctionName());
                    }
                    sb.Append(" [source name: ");
                    sb.Append(sof.getSourceName());
                    sb.Append("] [encoded source length: ");
                    sb.Append(sof.getEncodedSourceEnd()
                              - sof.getEncodedSourceStart());
                    sb.Append("] [base line: ");
                    sb.Append(sof.getBaseLineno());
                    sb.Append("] [end line: ");
                    sb.Append(sof.getEndLineno());
                    sb.Append(']');
                }
                if (((Node.Scope)this).symbolTable != null) {
                    sb.Append(" [scope ");
                    appendPrintId(this, printIds, sb);
                    sb.Append(": ");
                    IEnumerator<String> iter =
                        ((Node.Scope)this).symbolTable.Keys.GetEnumerator();
                    while (iter.MoveNext()) {
                        sb.Append(iter.Current);
                        sb.Append(" ");
                    }
                    sb.Append("]");
                }
            } else if (this is Jump) {
                Jump jump = (Jump)this;
                if (type == Token.BREAK || type == Token.CONTINUE) {
                    sb.Append(" [label: ");
                    appendPrintId(jump.getJumpStatement(), printIds, sb);
                    sb.Append(']');
                } else if (type == Token.TRY) {
                    Node catchNode = jump.target;
                    Node finallyTarget = jump.getFinally();
                    if (catchNode != null) {
                        sb.Append(" [catch: ");
                        appendPrintId(catchNode, printIds, sb);
                        sb.Append(']');
                    }
                    if (finallyTarget != null) {
                        sb.Append(" [finally: ");
                        appendPrintId(finallyTarget, printIds, sb);
                        sb.Append(']');
                    }
                } else if (type == Token.LABEL || type == Token.LOOP
                           || type == Token.SWITCH)
                {
                    sb.Append(" [break: ");
                    appendPrintId(jump.target, printIds, sb);
                    sb.Append(']');
                    if (type == Token.LOOP) {
                        sb.Append(" [continue: ");
                        appendPrintId(jump.getContinue(), printIds, sb);
                        sb.Append(']');
                    }
                } else {
                    sb.Append(" [target: ");
                    appendPrintId(jump.target, printIds, sb);
                    sb.Append(']');
                }
            } else if (type == Token.NUMBER) {
                sb.Append(' ');
                sb.Append(getDouble());
            } else if (type == Token.TARGET) {
                sb.Append(' ');
                appendPrintId(this, printIds, sb);
            }
            if (lineno != -1) {
                sb.Append(' ');
                sb.Append(lineno);
            }

            for (PropListItem x = propListHead; x != null; x = x.next) {
                int type1 = x.type;
                sb.Append(" [");
                sb.Append(propToString(type1));
                sb.Append(": ");
                String value;
                switch (type1) {
                  case TARGETBLOCK_PROP : // can't add this as it recurses
                    value = "target block property";
                    break;
                  case LOCAL_BLOCK_PROP :     // can't add this as it is dull
                    value = "last local block";
                    break;
                  case ISNUMBER_PROP:
                    switch (x.intValue) {
                      case BOTH:
                        value = "both";
                        break;
                      case RIGHT:
                        value = "right";
                        break;
                      case LEFT:
                        value = "left";
                        break;
                      default:
                        throw Kit.codeBug();
                    }
                    break;
                  case SPECIALCALL_PROP:
                    switch (x.intValue) {
                      case SPECIALCALL_EVAL:
                        value = "eval";
                        break;
                      case SPECIALCALL_WITH:
                        value = "with";
                        break;
                      default:
                        // NON_SPECIALCALL should not be stored
                        throw Kit.codeBug();
                    }
                    break;
                  case OBJECT_IDS_PROP: {
                    Object[] a = (Object[]) x.objectValue;
                    value = "[";
                    for (int i=0; i < a.Length; i++) {
                        value += a[i].ToString();
                        if (i+1 < a.Length)
                            value += ", ";
                    }
                    value += "]";
                    break;
                  }
                  default :
                    Object obj = x.objectValue;
                    if (obj != null) {
                        value = obj.ToString();
                    } else {
                        value = x.intValue.ToString();
                    }
                    break;
                }
                sb.Append(value);
                sb.Append(']');
            }
        }
    }


        private static void generatePrintIds(Node n, ObjToIntMap map)
        {
            if (Token.printTrees)
            {
                map.put(n, map.size());
                for (Node cursor = n.getFirstChild(); cursor != null;
                     cursor = cursor.getNext())
                {
                    generatePrintIds(cursor, map);
                }
            }
        }

        private static void appendPrintId(Node n, ObjToIntMap printIds,
                                          StringBuilder sb)
        {
            if (Token.printTrees)
            {
                if (n != null)
                {
                    int id = printIds.get(n, -1);
                    sb.Append('#');
                    if (id != -1)
                    {
                        sb.Append(id + 1);
                    }
                    else
                    {
                        sb.Append("<not_available>");
                    }
                }
            }
        }




        public String toStringTree(ScriptOrFnNode treeTop)
        {
            if (Token.printTrees)
            {
                StringBuilder sb = new StringBuilder();
                toStringTreeHelper(treeTop, this, null, 0, sb);
                return sb.ToString();
            }
            return null;
        }

        private static void toStringTreeHelper(ScriptOrFnNode treeTop, Node n,
                                               ObjToIntMap printIds,
                                               int level, StringBuilder sb)
        {
            if (Token.printTrees)
            {
                if (printIds == null)
                {
                    printIds = new ObjToIntMap();
                    generatePrintIds(treeTop, printIds);
                }
                for (int i = 0; i != level; ++i)
                {
                    sb.Append("    ");
                }
                n.toString(printIds, sb);
                sb.Append('\n');
                for (Node cursor = n.getFirstChild(); cursor != null;
                     cursor = cursor.getNext())
                {
                    if (cursor.getType() == Token.FUNCTION)
                    {
                        int fnIndex = cursor.getExistingIntProp(Node.FUNCTION_PROP);
                        FunctionNode fn = treeTop.getFunctionNode(fnIndex);
                        toStringTreeHelper(fn, fn, null, level + 1, sb);
                    }
                    else
                    {
                        toStringTreeHelper(treeTop, cursor, printIds, level + 1, sb);
                    }
                }
            }
        }






        private PropListItem propListHead;
        public int type;              // type of the node; Token.NAME for example
        public Node next;             // next sibling
        private Node first;    // first element of a linked list of children
        private Node last;     // last element of a linked list of children
        protected int lineno = -1;

        public static int END_UNREACHED = 0;
        public static int END_DROPS_OFF = 1;
        public static int END_RETURNS = 2;
        public static int END_RETURNS_VALUE = 4;
        public static int END_YIELDS = 8;
        #endregion
    }// end for class
}
